/* 
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.appspot.dispotrains;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.appspot.dispotrains.station.Elevator;
import com.appspot.dispotrains.station.ElevatorAdapter;
import com.appspot.dispotrains.station.Station;
import com.appspot.dispotrains.station.StationBuilder;

import java.util.Formatter;

public class GareDetailFragment extends ListFragment
    implements LoaderManager.LoaderCallbacks<Station> {

  public static final String ARG_ITEM_ID = "item_id";
  private static final String STATE_ACTIVATED_POSITION = "activated_position";

  private int mActivatedPosition = ListView.INVALID_POSITION;

  private Station mItem;

  public GareDetailFragment() {}

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);

    if (mItem != null) {
      savedInstanceState.putSerializable("station", mItem);
    }
  }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
      setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
    }
  }

  public void setActivatedPosition(int position) {
    if (position == ListView.INVALID_POSITION) {
      getListView().setItemChecked(mActivatedPosition, false);
    } else {
      getListView().setItemChecked(position, true);
    }

    mActivatedPosition = position;
  }


  @SuppressWarnings("unchecked")
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState != null && savedInstanceState.containsKey("station")) {
      mItem = (Station) savedInstanceState.getSerializable("station");
    }

    if (mItem == null) {
      getLoaderManager().initLoader(0, null, this);
    }
  }

  private void updateShareIntend() {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);

    int count = 0;
    for (Elevator elevator : mItem.getElevators()) {
      if (!elevator.status.equalsIgnoreCase("disponible")) {
        count++;
      }
    }

    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);

    if (count == 0) {
      formatter.format(
          "Gare de %s : tous les ascenseurs en service (via DispoTrains).", mItem.name);
    } else {
      formatter.format("Gare de %s : %d sur %d ascenseur(s) en panne (via DispoTrains).",
          mItem.name, count, mItem.getElevators().size());
    }
    intent.putExtra(Intent.EXTRA_TEXT, sb.toString());

    intent.setType("text/plain");
    if (GareDetailActivity.class.isInstance(getActivity())) {
      ((GareDetailActivity) getActivity()).setShareIntent(intent);
    }
  }

  /**
   * @see android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader(int,
   *      android.os.Bundle)
   */
  @Override
  public Loader<Station> onCreateLoader(int id, Bundle savedInstanceState) {
    return new StationBuilder(getActivity(), getArguments().getInt(ARG_ITEM_ID));
  }

  /**
   * @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.support.v4.content.Loader,
   *      java.lang.Object)
   */
  @TargetApi(11)
  @Override
  public void onLoadFinished(Loader<Station> arg0, Station station) {
    if (station == null) {
      CharSequence text = "Impossible de se connecter. Vérifiez votre connection et recommencez.";
      int duration = Toast.LENGTH_LONG;

      Toast toast = Toast.makeText(getActivity(), text, duration);
      toast.show();
      return;
    }

    mItem = station;
    if (Build.VERSION.SDK_INT >= 11) {
      ActionBar actionBar = getActivity().getActionBar();
      actionBar.setSubtitle(station.name);
    } else {
      getActivity().setTitle(station.name);
    }
    updateShareIntend();
    ElevatorAdapter adapter = new ElevatorAdapter(getActivity(), station);
    setListAdapter(adapter);
  }

  /**
   * @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.support.v4.content.Loader)
   */
  @Override
  public void onLoaderReset(Loader<Station> arg0) {
    // TODO(etiennej): Auto-generated method stub

  }
}
